package com.iss.examsys.view.util;

import com.iss.examsys.ejb.SubjectTagBean;
import com.iss.examsys.entity.SubjectTag;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author MA
 */
@FacesConverter("tagConverter")
public class TagConverter implements Converter {
    
    @EJB private SubjectTagBean subjectTagBean;
 
    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if(value != null && value.trim().length() > 0) {
            try {               
                return subjectTagBean.findById(Long.parseLong(value));
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid tag."));
            }
        }
        else {
            return null;
        }
    }
 
    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if(object != null) {
            return String.valueOf(((SubjectTag) object).getId());
        }
        else {
            return null;
        }
    }   
}     

